import { h, render } from 'vue'
import Overlay from 'ol/Overlay.js'

class Popup {
  static overlays = []
  constructor(options, mapView, mul = false) {
    this.mapView = mapView
    this.container = null
    this.overlay = null
    this.vueInstance = null
    this.mul = mul
    this.init(options)
    Popup.overlays.push(this)
  }

  init(options) {
    const { component, coordinate, content } = options
    if (!this.mul) {
      for (let overlay of Popup.overlays) {
        console.log("ol:", overlay)
        overlay.close()
      }
      
    }
    // 创建容器
    this.container = document.createElement('div')
    this.container.className = 'ol-popup-container'

    // 创建Overlay
    this.overlay = new Overlay({
      element: this.container,
      autoPan: {
        animation: { duration: 250 }
      },
      positioning: 'bottom-center',
      stopEvent: true
    })

    // 渲染Vue组件
    if (component) {
      this.vueInstance = h(component, {
        content:  content,
        onClick: () => this.close()
      })
      render(this.vueInstance, this.container)
    }

    // 添加到地图
    this.overlay.setPosition(coordinate)
    this.mapView.addOverlay(this.overlay)

  }

  close() {
    if (this.overlay) {
      this.overlay.setPosition(undefined)
    }
    this.destroy()
  }

  destroy() {
    // 清理Vue组件
    if (this.container) {
      render(null, this.container)
    }

    // 移除Overlay
    if (this.overlay) {
      this.mapView.removeOverlay(this.overlay)
      this.overlay = null
    }

    // 移除DOM容器
    if (this.container && this.container.parentNode) {
      this.container.parentNode.removeChild(this.container)
      this.container = null
    }
  }

  // 可选：添加更新位置的方法
  setPosition(coordinate) {
    if (this.overlay) {
      this.overlay.setPosition(coordinate)
    }
  }
}

export default Popup
